<template>
<div>
  <el-row>
  <el-col :span="6">
    <el-row style="margin-bottom:23px;">
      <el-button v-if="isAuth('app:service:save')" type='primary' @click="addOrUpdateHandle(1)"  :disabled="btnshowflag" >添加</el-button>
      <el-button v-if="isAuth('app:service:update')" type='success'  @click="addOrUpdateHandle(2)"  :disabled="btnshowflag" >{{ $t('handle.update') }}</el-button>
      <el-button  v-if="isAuth('batch:delete')" type="danger"  @click="menuDelete()"  :disabled="btnDelflag" >{{ $t('handle.delete') }}</el-button>
    </el-row>

    <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
      <el-tree
        :props = "props1"
        :load = "loadNode"
        @node-click = "clickNode"
        :filter-node-method = "filterNode"
        :highlight-current='true'
        :expand-on-click-node = false
        :default-expand-all = false
        lazy
        node-key ="id"
        ref ="tree">
      </el-tree>
  </el-col>

  <el-col :span="17" style="margin-left:10px;">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item v-if="superAdmin == 1" >
        <el-cascader style="width: 100%;"
          @visible-change.native="test"
          @click.native="getOne"
          placeholder="请选择小区"
          clearable
          :change-on-select="false"
          v-model="address"
          :options="options"
          :show-all-levels="false"
          @active-item-change="getNodes"
          :props="props">
        </el-cascader>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.name" placeholder="名称" clearable></el-input>
      </el-form-item>
      <!-- <el-form-item>
        <el-select v-model="dataForm.housingEstateId" filterable  placeholder="请选择" style="width:185px;">
         <el-option
          v-for="(item,index) in selectHousingEstate"
          :key="index"
          :label="item.fullName"
          :value="item.id">
          </el-option>
      </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button @click="getDataList()">{{ $t('handle.search') }}</el-button>
        <!--v-if="isAuth('')"是权限的控制-->
        <el-button v-if="isAuth('app:service:save')" type='primary' @click="addHandle()"  :disabled="servicebtnshowflag" >添加</el-button>
        <!-- <el-button  type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">{{ $t('handle.batchDelete') }}</el-button> -->
      </el-form-item>
    </el-form>

     <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="index"
        header-align="center"
        align="center"
       :label="$t('tabble.No')"
        width="50">
      </el-table-column>
      <el-table-column
        prop="housingEasteName"
        header-align="center"
        :show-overflow-tooltip = true
        align="center"
        label="所属小区">
      </el-table-column>
      <el-table-column
        prop="icon"
        header-align="center"
        align="center"
        label="图标">
        <template slot-scope="scope">
          <!-- <span style="color:red;">{{ scope.row.icon }}</span> -->
          <img :src=" imgUrlHost + scope.row.icon" style="width:30%" />
          <!-- <img src="./momey.png" style="width:30%" /> -->
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        header-align="center"
        align="center"
        label="服务名称">
      </el-table-column>
      <!-- <el-table-column
        prop="type"
        header-align="center"
        align="center"
        label="类型">
        <template slot-scope="scope">
          <span>{{ServiceType(scope.row.type)}}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        header-align="center"
        align="center"
        label="首页展示">
         <template slot-scope="scope">
          <el-switch
          v-model="scope.row.showIndex"
          :active-text="switchshowIndex.activeText"
          :active-value="switchshowIndex.activeValue"
          :inactive-text="switchshowIndex.inactiveText"
          :inactive-value="switchshowIndex.inactiveValue"
          @change="updateShowIndex($event, scope.row)"
          >
          </el-switch>
         </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        label="登录使用">
         <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isAuth"
            :active-text="switchIsAuth.activeText"
            :active-value="switchIsAuth.activeValue"
            :inactive-text="switchIsAuth.inactiveText"
            :inactive-value="switchIsAuth.inactiveValue"
            @change="updateIsAuth($event, scope.row)"
            style="align:center"
              >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="sort"
        header-align="center"
        align="center"
        :label="$t('tabble.sort')">
      </el-table-column>
      <el-table-column
        prop="status"
        header-align="center"
        align="center"
        :label="$t('status.status')">
        <template slot-scope="scope">
          <el-tag
          :type="scope.row.status == 2 ? 'danger' : scope.row.status == 9? 'warning':'success' "
          >{{ServiceStatus(scope.row.status)}}</el-tag>
          <!-- <span>{{dictTypeFilter(scope.row.status)}}</span> -->
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="createDate"
        header-align="center"
        align="center"
        label="创建时间">
      </el-table-column> -->

      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        :label="$t('handle.handle')">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="addHandle(scope.row.id)">{{ $t('handle.update') }}</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">{{ $t('handle.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
  </el-col>
  </el-row>
  <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
</div>
</template>

<script>
  import AddOrUpdate from './appservice-add-or-update'
  import { isAuth } from '@/utils'
  import { getHousingEstate } from '@/utils'
  import { imgUrlHost } from '@/config/env'
  import {
      getOne,
      getTwo,
      getThree,
      getFour,
      getFive,
      getSix
    } from "@/utils/questUtils";
  export default {
    watch: {
      filterText (val) {
        this.$refs.tree.filter(val)
      }
    },
    data () {
      return {
        // 搜索过滤的值
        filterText: '',
        imgUrlHost:imgUrlHost,
        superAdmin: sessionStorage.getItem("superAdmin"),
        options: [],
        address:[],
        selectHousingEstate: [],
        dataForm: {
          name: '',
          housingEstateId: ''
        },
        props1: {
          label: 'name',
          children: 'page',
          isLeaf: 'isLeaf'
        },
        props: {
          value: "id",
          label: "name",
          children: "children"
        },
        checkId: '',
        btndelflag: true,
        btnshowflag: true,
        servicebtnshowflag: true,
        btnDelflag: true,
        checkName: '',
        addOrUpdateVisible: false,
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        ServiceTypeAry: [],
        switchshowIndex: {
          activeText: '',
          activeValue: '',
          inactiveText: '',
          inactiveValue: ''
        },
        switchIsAuth: {
          activeText: '',
          activeValue: '',
          inactiveText: '',
          inactiveValue: ''
        },
        ServiceStatusAry: []
      }
    },
    computed: {
      ServiceType () {
        return function (type) {
          return this.ServiceTypeAry[type]
        }
      },
      ServiceStatus () {
        return function (type) {
          return this.ServiceStatusAry[type]
        }
      }
    },
    created () {
      this.getServiceType()
      this.getServiceStatus()
      this.getServiceIsAuth()
      this.getServiceShowIndex()
      this.getHousingEstate()
    },
    components: {
      AddOrUpdate
    },
    methods: {
      getHousingEstate () {
        this.$http({
          // url: this.$http.adornUrl(`/ic/dict/type/service_status`),
          url: '/dg-ic/ic/housing-estate/list',
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            // console.log(data)
            this.selectHousingEstate = data.data.list
          }
        })
      },
      updateShowIndex (val, row) {
        this.$http({
          // url: this.$http.adornUrl('/ic/appservice/updatestatus'),
          url: '/dg-ic/ic/appservice/updatestatus',
          method: 'get',
          params: this.$http.adornParams({
            'showIndex': row.showIndex,
            'id': row.id
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.getDataList()
          } else {
            this.$message.error('修改失败')
          }
        })
      },
      updateIsAuth (val, row) {
        this.$http({
          // url: this.$http.adornUrl('/ic/appservice/updatestatus'),
          url: '/dg-ic/ic/appservice/updatestatus',
          method: 'get',
          params: this.$http.adornParams({
            'isAuth': row.isAuth,
            'id': row.id
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.getDataList()
          } else {
            this.$message.error('修改失败')
          }
        })
      },
      loadNode (node, resolve) {
        if (node.level === 0) {
          // return resolve([{ id: '1', name: '社区服务' }])
          this.getTreeData(null, resolve)
        } else {
          this.getTreeData(node.data.id, resolve)
        }
      },
      getTreeData (id, resolve) {
        //console.log(sessionStorage .getItem('superAdmin'))
       // console.log(sessionStorage.getItem('thiscommunityId'))
        this.$http({
          // url: this.$http.adornUrl(`/ic/appservice/list`),
          url: `/dg-ic/ic/appservice/list`,
          method: 'get',
          params: this.$http.adornParams({
            'pid': id,
            'housingEstateId': sessionStorage.getItem("superAdmin") == 1
              ? this.address[this.address.length - 1]
              : sessionStorage.getItem("thiscommunityId") || "",
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.btndelflag = false
            data.page.map(function (item) {
              if (item.isLeaf === 2 || item.isLeaf === null) {
                item.isLeaf = false
              }else {
                item.isLeaf = true
              }
              return item;
            })
            return resolve(data.page)
          }
        })
      },
       // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      filterNode (value, data) {
        if (!value) return true
        return data.name.indexOf(value) !== -1
      },
      add () {
        this.dataForm.parentId = this.checkId
        this.dataForm.parentName = this.checkName
      },
      update () {
        this.dataForm.id = this.checkId
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
       // 新增 / 修改
      addOrUpdateHandle (value) {
        let id = 0
        let pid = 0
        let pname = ''
        if (value === 1) { // 添加
          pid = this.checkId
          pname = this.checkName
        } else {
          id = this.checkId
        }
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id, pid, pname, 1)
        })
      },
      addHandle (id) {
        // console.log(this.checkId, this.checkName)
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id, this.checkId, this.checkName, 2)
        })
      },
      cleanFrom () {
        this.dataForm.id = this.checkId
      },
      clickNode (node, data, value) {
        this.servicebtnshowflag = true
        this.btnshowflag = false
        if(node.id === '1'){
          this.servicebtnshowflag = true
        }else {
          this.servicebtnshowflag = false
        }
        this.checkId = node.id
        this.checkName = node.name
		    this.global.setTreeNode(data)
        this.global.setRefreshNode(this.refreshNode)
        this.getDataList()
      },
	  refreshNode(node){
        this.$http({
         // url: this.$http.adornUrl(`/dgstandardaddress/childlistbyparentid/${node.data.id}`),
		      url: `/dg-ic/ic/appservice/list`,
              method: 'get',
              params: this.$http.adornParams({
				      'pid': node.data.id,
			         })
            }).then(({data}) => {
              if (data && data.code === 0) {
                node.loaded = true;
                node.loading = false;
                node.childNodes = [];
                data.page.map(function (item) {
                  if (item.isLeaf === 2) {
                      item.isLeaf = false
                  }else {
                      item.isLeaf = true
                  }
                  return item;
                })
                node.doCreateChildren(data.page);
                node.updateLeafState();
                node.expanded = true
                }
            })

      },
      getDataList () {
        this.dataListLoading = true
        // console.log(this.address[this.address.length - 1])
        // console.log(this.address)
        this.$http({
          // url: this.$http.adornUrl('/ic/appservice/servicelist'),
          url: '/dg-ic/ic/appservice/servicelist',
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'pid': this.checkId,
            'name': this.dataForm.name,
            // 'housingEstateId':sessionStorage .getItem('superAdmin') ==1?this.address[this.address.length-1]:sessionStorage .getItem('thiscommunityId') || '',
            'housingEstateId': sessionStorage .getItem('superAdmin') ==1?this.address[this.address.length - 1]:sessionStorage.getItem('thiscommunityId') || '',
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            // console.log(data)
            this.btnDelflag = true
            // data.list.map(function (item) {
            //  getHousingEstate(item.housingEstateId).then(({data}) => {
              //    item.housingEstateId = data.data.fullName
            //  })
             // return item
           // })
            this.dataList = data.list
            if (data.list.length === 0) {
               this.btnDelflag = false
            }
            this.totalPage = data.count
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      getServiceType () {
        this.$http({
          // url: this.$http.adornUrl(`/ic/dict/type/service_type`),
          url: '/dg-ic/ic/dict/type/service_type',
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            for (let i = 0; i < data.data.length; i++) {
              this.ServiceTypeAry[data.data[i].value] = data.data[i].label
            }
          }
        })
      },
      getServiceStatus () {
        this.$http({
          // url: this.$http.adornUrl(`/ic/dict/type/service_status`),
          url: '/dg-ic/ic/dict/type/service_status',
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            for (let i = 0; i < data.data.length; i++) {
              this.ServiceStatusAry[data.data[i].value] = data.data[i].label
            }
          }
        })
      },
      getServiceIsAuth () {
        this.$http({
          // url: this.$http.adornUrl(`/ic/dict/type/service_isauth`),
          url: '/dg-ic/ic/dict/type/service_isauth',
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.switchIsAuth.activeText = data.data[1].label
            this.switchIsAuth.activeValue = parseInt(data.data[1].value)
            this.switchIsAuth.inactiveText = data.data[0].label
            this.switchIsAuth.inactiveValue = parseInt(data.data[0].value)
          }
        })
      },
      getServiceShowIndex () {
        this.$http({
          // url: this.$http.adornUrl(`/ic/dict/type/service_showindex`),
          url: '/dg-ic/ic/dict/type/service_showindex',
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.switchshowIndex.activeText = data.data[0].label
            this.switchshowIndex.activeValue = parseInt(data.data[0].value)
            this.switchshowIndex.inactiveText = data.data[1].label
            this.switchshowIndex.inactiveValue = parseInt(data.data[1].value)
          }
        })
      },
      menuDelete () {
        let ids = [this.checkId]
        this.$confirm(`确定对${this.checkName}删除操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
           // url: this.$http.adornUrl('/ic/appservice/delete'),
            url: '/dg-ic/ic/appservice/delete',
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  // this.getDataList()
                   this.global.refreshNode(this.global.treeNode.parent);
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
           // url: this.$http.adornUrl('/ic/appservice/delete'),
            url: '/dg-ic/ic/appservice/delete',
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
       // 一级
    getOne() {
      getOne().then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options = response.data.page;
        }
      });
    },
    // 二级
    getTwo(countryId) {
      getTwo(countryId).then(response => {
        if (response.data.page && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map(item => {
            if (item.id === countryId) {
              item.children = response.data.page;
            }
          });
        }
      });
    },
    getThree(countryId, provinceId) {
      getThree(provinceId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((city, id) => {
                city.children = response.data.page;
              });
            }
          });
        }
      });
    },
    getFour(countryId, provinceId, cityId) {
      getFour(cityId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    city.children = response.data.page;
                  });
                }
              });
            }
          });
        }
      });
    },
    getFive(countryId, provinceId, cityId, areaId) {
      getFive(areaId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    if (city.id === cityId) {
                      city.children.map((area, aid) => {
                        area.children = response.data.page;
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
    },
    getSix(countryId, provinceId, cityId, areaId, communityCodeId) {
      getSix(communityCodeId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            // this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    if (city.id === cityId) {
                      city.children.map((area, aid) => {
                        if (area.id === areaId) {
                          area.children.map((communt, ic) => {
                            communt.children = response.data.page;
                          });
                        }
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
    },
    getNodes(val) {
        if (val.length === 1) {
          // 获取省
          this.getTwo(val[0]);
        } else if (val.length === 2) {
          // 市
          this.getThree(val[0], val[1]);
        } else if (val.length === 3) {
          // 区
          this.getFour(val[0], val[1], val[2]);
        } else if (val.length === 4) {
          this.getFive(val[0], val[1], val[2], val[3]); //社区
        } else if (val.length === 5) {
          this.getSix(val[0], val[1], val[2], val[3], val[4]); // 小区
        }
        //如果继续添加下级，类似这样继续添加即可
      }
    }
  }
</script>
